const lodash = require('lodash/lodash')
const findDeep = require('deepdash/getFindDeep')(lodash)
const eachDeep = require('deepdash/getEachDeep')(lodash)
const treeData = require('./treeData')

const node = {
  name: 'level4',
  value: 40
}

const propMap = {
  keyProp: 'value',
  childrenProp: 'children',
  includeSelf: true
}

function sameDepth (treeData, node, propMap) {
  const deepOptions = {
    childrenPath: propMap.childrenProp
  }
  const searchValue = node[propMap.keyProp]
  const targetMeta = findDeep(treeData, function (item, key, parent) {
    const itemValue = item[propMap.keyProp]
    if (itemValue === searchValue) return true
  }, deepOptions)

  if (!targetMeta) return []
  const { context: { depth } } = targetMeta

  const result = []
  eachDeep(treeData, (val, key, parent, context) => {
    if (context.depth === depth) {
      result.push(val)
      if (!propMap.includeSelf && searchValue === val[propMap.keyProp]) result.pop()
    }
  } , deepOptions)
  // return propMap.includeSelf ? result : result.filter(item => item[propMap.keyProp] !== searchValue)
  return result
}


const sameDepthValues = sameDepth(treeData, node, propMap)

console.log(`same depth of node ${node.name}: \n`, sameDepthValues)

